package edu.ucla.hmcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

public class Client {
	
	public static String rootIpAddr = null;
	public static Timer rootTimer = new Timer();
	
	public static Socket hmcpSocket = null;
	public static PrintWriter out = null;
	public static BufferedReader in = null;
	
	public static void main(String[] args) throws IOException {
		
		String rendezvousServer = null; 
		
		if(args.length < 1) {
			rendezvousServer = "localhost";
			System.out.println("No host provided for rendezvous server, using localhost\nConnecting to localhost");
		} else {
			rendezvousServer = args[0];
			System.out.println("Connecting to provided rendezvous server: " + rendezvousServer);
		}
		
        try {
        	hmcpSocket = new Socket(rendezvousServer, 4444);
            out = new PrintWriter(hmcpSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(hmcpSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + rendezvousServer);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " + rendezvousServer);
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;

        // Get IP Address of this machine
        InetAddress localhostIp =InetAddress.getLocalHost();
		String ipAddr = localhostIp.getHostAddress();
		
		// Say HELLO to the Rendezvous Server to find out who the root is
        out.println("HELLO"+ipAddr);
        
        while ((fromServer = in.readLine()) != null) {
        	System.out.println("fromServer="+fromServer);
        	if(fromServer.equals(ipAddr)) {
        		int delay = 0;
        		int period = 1000;
        		
        		rootTimer.scheduleAtFixedRate(new TimerTask() {
        			public void run() {
        				out.println("REFRESH");
        			}
        		}, delay, period);
        	} else {
        		System.out.println("The root is: " + rootIpAddr);
        		rootIpAddr = fromServer;
        		// Connect to root server located at rootIpAddr
        	}
        
        }
        

        out.close();
        in.close();
        stdIn.close();
        hmcpSocket.close();
	}
}

